package com.qf.application.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.application.commons.exception.BusinessException;
import com.qf.application.commons.utils.R;
import com.qf.application.entity.Menu;
import com.qf.application.service.IMenuService;
import com.qf.application.service.IMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/menu")
public class MenuController {

    @Autowired
    private IMenuService menuService;

    @GetMapping("/tree/{root}")
    public R tree(@PathVariable Integer root) {
        List<Map<String, Object>> maps = menuService.treeDate(root);
        // 2.封装数据返回给前端
        return R.ok().put("data", maps);
    }

    @GetMapping("/list")
    public R list() {
        return R.ok().put("data", menuService.list());
    }

    @PostMapping("/page")
    public R page(@RequestBody Page<Menu> page) {
        return R.ok(menuService.page(page));
    }

    @PostMapping("/save")
    public R save(@RequestBody Menu menu) {
        return R.write(menuService.save(menu));
    }

    @PostMapping("/update")
    public R update(@RequestBody Menu menu) {
        return R.write(menuService.updateById(menu));
    }

    @GetMapping("/info/{id}")
    public R info(@PathVariable Integer id) {
        return R.ok(menuService.info(id));
    }

    @PostMapping("/remove")
    public R remove(@RequestBody List<Integer> midList) {

        // 1.查询删除的菜单下面是否有子菜单
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.in("pid", midList); // select count(1) from t_menu where pid in (1,2,3)
        long count = menuService.count(wrapper);
        if (count > 0) {
            throw new BusinessException(1001, "您删除的菜单下面有子菜单，请先删除子菜单");
        }
        return R.write(menuService.removeBatchByIds(midList));
    }
}
